<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2018/6/1
 * Time: 9:57
 */

namespace App\Repository;


use App\Exceptions\BusinessException;
use App\Exceptions\ValidatorException;
use App\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class UserRepository
{

    /**
     * 增加用户
     *
     * @param array $data
     * @return mixed
     * @throws ValidatorException
     */
    public function addUser(array $data)
    {
        $this->validator($data);
        $data['password'] = Hash::make($data['password']);
        $data['begin_at'] = date('Y-m-d H:i:s', strtotime($data['begin_at'])) ?? Carbon::create(1970, 01, 01);
        $data['end_at'] = $data['end_at'] ?
            date('Y-m-d H:i:s', strtotime($data['end_at'])) :
            Carbon::create(2028, 01, 01);

        DB::beginTransaction();
        try {
            $user = User::create($data);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('注册用户失败: '. $e->getMessage(), $data);
            throw new BusinessException(BusinessException::SERVER_ERROR, '服务器开小差了', 500);
        }
        return $user;
    }

    /**
     * 用户列表
     * @param int $offset
     * @param int $range
     * @param array $params
     * @return array
     */
    public function userList(int $offset = 0, int $range = 15, array $params = [])
    {
        $query = User::query()
            ->where('is_able', '!=', 3)
            ->when(!empty($params['name']), function ($query) use ($params) {
                $query->where('name', 'like', '%' . $params['name'] . '%');
            })->when(!empty($params['phone']), function ($query) use ($params) {
                $query->where('phone', $params['phone']);
            })->orderBy('id', 'desc');

        return [
            'range' => $range,
            'offset' => $offset,
            'total' => $query->count(),
            'params' => $params,
            'items' => $query->offset($offset)->limit($range)->get()
        ];
    }

    /**
     * 修改用户
     *
     * @param int $userID
     * @param array $data
     * @return bool
     */
    public function userEdit(int $userID, array $data)
    {
        if (!empty($data['password'])) {
            $data['password'] = Hash::make($data['password']);
        }

        if (!empty($data['begin_at'])) {
            $data['begin_at'] = date('Y-m-d H:i:s', strtotime($data['begin_at']));
        }

        if (!empty($data['end_at'])) {
            $data['end_at'] = date('Y-m-d H:i:s', strtotime($data['end_at']));
        }
        DB::beginTransaction();
        try {
            $user = User::query()->findOrFail($userID)->update($data);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('修改用户失败: ' . $e->getMessage(), $data);
            throw new BusinessException(BusinessException::SERVER_ERROR, '服务器开小差了', 500);
        }
        return $user;
    }

    /**
     * 表单验证
     *
     * @param array $data
     * @return bool
     * @throws ValidatorException
     */
    private function validator(array $data)
    {
        $validator = Validator::make($data, [
            'name' => 'required|min:2',
            'password' => 'required|min:6',
            'phone' => [
                'required',
                'regex:/^1[345789][0-9]{9}$/',
                'numeric',
                'unique:users'
            ],
        ], [
            'required' => ':attribute 不能为空',
            'min' => ':attribute 长度不符合',
            'regex' => '请输入正确的:attribute',
            'unique' => '手机号码已存在'
        ], [
            'name' => '姓名',
            'password' => '密码',
            'phone' => '手机号码',
        ]);

        if ($validator->fails()) {
            throw new ValidatorException($validator);
        }
        return true;
    }
}